#include "ddl.h"
#include "gpio.h"
#include "timer3.h"


#include "led.h"
#include "QG_driver.h"

extern uint8_t QG_state_start;
extern uint8_t QG_timer_start;

void timer3_init(uint16_t u16Period)
{
	uint16_t                    u16ArrValue;
     uint16_t                    u16CntValue;
     stc_tim3_mode0_cfg_t        stcTim3BaseCfg;
     
     //结构体初始化清零
     DDL_ZERO_STRUCT(stcTim3BaseCfg);
     
     Sysctrl_SetPeripheralGate(SysctrlPeripheralTim3, TRUE); //Base Timer外设时钟使能
     
     stcTim3BaseCfg.enWorkMode = Tim3WorkMode0;              //定时器模式
     stcTim3BaseCfg.enCT       = Tim3Timer;                  //定时器功能，计数时钟为内部PCLK
     stcTim3BaseCfg.enPRS      = Tim3PCLKDiv64;              //PCLK/64
     stcTim3BaseCfg.enCntMode  = Tim316bitArrMode;           //自动重载16位计数器/定时器
     stcTim3BaseCfg.bEnTog     = FALSE;
     stcTim3BaseCfg.bEnGate    = FALSE;
     stcTim3BaseCfg.enGateP    = Tim3GatePositive;
     
     Tim3_Mode0_Init(&stcTim3BaseCfg);                       //TIM3 的模式0功能初始化
          
     u16ArrValue = 0x10000 - u16Period;
     
     Tim3_M0_ARRSet(u16ArrValue);                            //设置重载值(ARR = 0x10000 - 周期)
     
     u16CntValue = 0x10000 - u16Period;
     
     Tim3_M0_Cnt16Set(u16CntValue);                          //设置计数初值
     
     Tim3_ClearIntFlag(Tim3UevIrq);                          //清中断标志
     Tim3_Mode0_EnableIrq();                                 //使能TIM3中断(模式0时只有一个中断)
     EnableNvic(TIM3_IRQn, IrqLevel3, TRUE);                 //TIM3 开中断 
	Tim3_M0_Run();   		//TIM3 运行。
}

/*******************************************************************************
 * TIM3中断服务函数
 ******************************************************************************/
void Tim3_IRQHandler(void)
{
    static uint8_t i;
    static uint8_t counter;
    
    //Timer3 模式0 计时溢出中断
    if(TRUE == Tim3_GetIntFlag(Tim3UevIrq))
    {
          // counter++;
//          if(0 == i)
//          {
//               led_set(LED_ON);  //LED翻转
//               i++;
//          }
//          else
//          {
//               led_set(LED_OFF);  //LED翻转
//               i = 0;
//          }
//          if (QG_timer_start == 1)
//          {
//               counter++;
//               if (counter >= 60)
//               {
//                    QG_timer_start = 0;
//                    QG_info.state = 0;
//                    counter = 0;
//                    Gpio_EnableIrq(QG_STATE_PORT, QG_STATE_PIN, GpioIrqRising);
//               }
//          }
          Tim3_ClearIntFlag(Tim3UevIrq);  //Timer3模式0 中断标志清除
    }
}

